package com.asiainfo.iov.activity;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asiainfo.iov.configs.ConstantsME;
import com.asiainfo.iov.configs.InterfaceConfig;
import com.asiainfo.iov.networkModel.HttpUtil;
import com.framework.customviews.OverScrollView;
import com.framework.security.RSAmethodInAssets;
import com.framework.utils.KeyBoardUtil;
import com.framework.utils.PreferencesHelper;
import com.framework.utils.RegularUtil;
import com.framework.utils.ScreenUtils;
import com.framework.utils.ToastUtil;
import com.framework2.util.CustomLoadingDialogUtils;
import com.framework2.util.PicToastUtil;
import com.yaxin.yyt.R;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 注册
 * <p>
 * className RegisterActivity
 * created at  2017/3/15  11:30
 */
public class RegisterActivity extends BaseActivity {

    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.etLoginPhone)
    EditText etLoginPhone;
    @BindView(R.id.groupPhone)
    LinearLayout groupPhone;
    @BindView(R.id.etLoginCaptcha)
    EditText etLoginCaptcha;
    @BindView(R.id.tvCaptcha)
    TextView tvCaptcha;
    @BindView(R.id.groupCaptcha)
    LinearLayout groupCaptcha;
    @BindView(R.id.etSetPassword)
    EditText etSetPassword;
    @BindView(R.id.groupSetPwd)
    LinearLayout groupSetPwd;
    @BindView(R.id.tvNextStep)
    TextView tvNextStep;
    @BindView(R.id.tvRegister)
    TextView tvRegister;
    @BindView(R.id.overScrollView)
    OverScrollView overScrollView;
    @BindView(R.id.groupOtherLogin)
    RelativeLayout groupOtherLogin;
    private CaptchaCountDownTimer captchaCountDownTimer;
    private String verifyKey;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        ScreenUtils.getInstance().setSystemUiColorDark(this, false);//设置状态栏字体颜色浅
        captchaCountDownTimer = new CaptchaCountDownTimer(60000, 1000);
        initData();
        initUI();
    }

    private void initUI() {

    }

    private void initData() {
        ((OverScrollView) findViewById(R.id.overScrollView))
                .setOverScrollTinyListener(new OverScrollView.OverScrollTinyListener() {

                    @Override
                    public void scrollLoosen() {

                    }

                    @Override
                    public void scrollDistance(int tinyDistance,
                                               int totalDistance) {
                        KeyBoardUtil.getInstance().isCloseSoftInputMethod(RegisterActivity.this,
                                etLoginPhone, true);
                    }
                });
        String phoneTemp = RSAmethodInAssets.rsaDecrypt(this,
                PreferencesHelper.getInstance().getStringData(ConstantsME.PHONE_TEMP));
        long last = PreferencesHelper.getInstance().getLongData(ConstantsME.captcha_last_clicked);
        long currentTimeMillis = System.currentTimeMillis();
        long difference = currentTimeMillis - last;
        int diff = (int) ((60 * 1000 - difference) / 1000);
        if (difference < 60 * 1000 && diff >= 1) {
            if (!TextUtils.isEmpty(phoneTemp)) {
                etLoginPhone.setText(phoneTemp);
                etLoginPhone.setSelection(phoneTemp.length());
            }
            new CaptchaCountDownTimer(diff * 1000, 1000).start();
        } else {
            String phone = RSAmethodInAssets.rsaDecrypt(this,
                    PreferencesHelper.getInstance().getStringData(ConstantsME.PHONE));
            if (!TextUtils.isEmpty(phone)) {
                etLoginPhone.setText(phone);
                etLoginPhone.setSelection(phone.length());
                etLoginPhone.requestFocus();
                KeyBoardUtil.getInstance().isCloseSoftInputMethod(RegisterActivity.this, etLoginPhone, false);
            } else if (!TextUtils.isEmpty(getIntent().getStringExtra(ConstantsME.PHONE))) {
                etLoginPhone.setText(getIntent().getStringExtra(ConstantsME.PHONE));
                etLoginPhone.setSelection(getIntent().getStringExtra(ConstantsME.PHONE).length());
                etLoginPhone.requestFocus();
                KeyBoardUtil.getInstance().isCloseSoftInputMethod(RegisterActivity.this, etLoginPhone, false);
            }
        }
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvCaptcha:
                if (null == etLoginPhone.getText()
                        || "".equals(etLoginPhone.getText().toString())) {
                    PicToastUtil.getInstance().showToast(RegisterActivity.this, "请输入你的手机号码!");
                    etLoginPhone.requestFocus();
                    KeyBoardUtil.getInstance().isCloseSoftInputMethod(RegisterActivity.this, etLoginPhone,
                            false);
                } else if (!RegularUtil.getInstance().isMobileNO(etLoginPhone.getText().toString())) {
                    PicToastUtil.getInstance().showToast(RegisterActivity.this, "请输入正确的手机号码!");
                    etLoginPhone.requestFocus();
                    KeyBoardUtil.getInstance().isCloseSoftInputMethod(RegisterActivity.this, etLoginPhone,
                            false);
                } else {
                    PreferencesHelper.getInstance().putInfo(ConstantsME.PHONE_TEMP, RSAmethodInAssets.rsaEncrypt(this,
                            etLoginPhone.getText().toString()));
                    PreferencesHelper.getInstance().putInfo(ConstantsME.captcha_last_clicked, System
                            .currentTimeMillis());
                    captchaCountDownTimer.start();
                    CustomLoadingDialogUtils.showProcessDialog(RegisterActivity.this, "获取验证码");
                    requestCaptcha();
                }
                break;
            case R.id.tvNextStep:
//                verifyKey="test";
                KeyBoardUtil.getInstance().isCloseSoftInputMethod(RegisterActivity.this, etLoginPhone, true);
                PicToastUtil.getInstance().showToast(this, "显示下一步");
                showSetPasswordUI(true);
                break;
            case R.id.tvRegister:
//                verifyKey="test";
                KeyBoardUtil.getInstance().isCloseSoftInputMethod(RegisterActivity.this, etLoginPhone, true);
                if (isLegal(etLoginPhone, etLoginCaptcha)) {
                    if (TextUtils.isEmpty(verifyKey)) {
                        ToastUtil.getInstance().showToast("请先获取验证码");
                    } else {
                        CustomLoadingDialogUtils.showProcessDialog(RegisterActivity.this, "正在注册");
                        requestRegister(verifyKey);
                    }
                }
                break;
            case R.id.ivBack:
                back();
                break;
            default:
                break;
        }
    }

    private void showSetPasswordUI(boolean showSetPasswordUI) {
        tvNextStep.setVisibility(showSetPasswordUI ? View.GONE : View.VISIBLE);
        groupCaptcha.setVisibility(showSetPasswordUI ? View.GONE : View.VISIBLE);
        groupPhone.setVisibility(showSetPasswordUI ? View.GONE : View.VISIBLE);
        //下一步
        tvRegister.setVisibility(showSetPasswordUI ? View.VISIBLE : View.GONE);
        groupSetPwd.setVisibility(showSetPasswordUI ? View.VISIBLE : View.GONE);
    }

    /**
     * 请求获取验证码
     */
    private void requestCaptcha() {
        HttpUtil.getInstance().requestMobileVerify(InterfaceConfig.captcha, 1, etLoginPhone.getText().toString(),
                new HttpUtil.OnRequestResult<String>() {
                    @Override
                    public void onSuccess(String... s) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        ToastUtil.getInstance().showToast("获取验证码成功");
                        if (null != s && !TextUtils.isEmpty(s[0])) {
                            verifyKey = s[0];
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "获取验证码失败" : msg);
                        PreferencesHelper.getInstance().putInfo(ConstantsME.captcha_last_clicked, 0L);
                        if (null != captchaCountDownTimer)
                            captchaCountDownTimer.cancel();
                        tvCaptcha.setText("重新获取");
                        tvCaptcha.setTextColor(getResources().getColor(R.color._blue));
                        tvCaptcha.setClickable(true);
                    }
                });
    }

    /**
     * 请求注册
     */
    private void requestRegister(@NonNull String verifyKey) {
        HttpUtil.getInstance().requestRegister(InterfaceConfig.register, etLoginPhone.getText().toString(),
                etLoginCaptcha.getText().toString(), verifyKey, etLoginCaptcha.getText().toString(),
                new HttpUtil.OnRequestResult<String>() {
                    @Override
                    public void onSuccess(String... s) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        ToastUtil.getInstance().showToast("注册成功");
//                        registerSuccess();//TODO 验证码登录成功后
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "注册失败" : msg);
                    }
                });
    }

    /**
     * 返回
     */
    private void back() {
        KeyBoardUtil.getInstance().isCloseSoftInputMethod(this, null, true);
        if (!tvNextStep.isShown()) {
            finishActivity();
        } else {
            showSetPasswordUI(false);
        }
    }

    private boolean isLegal(EditText et_phone, EditText et_captcha) {
        if (null == et_phone)
            return false;
        if (TextUtils.isEmpty(et_phone.getText())) {
            PicToastUtil.getInstance().showToast(RegisterActivity.this, "请输入你的手机号码!");
            et_phone.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(RegisterActivity.this, et_phone, false);
            return false;
        } else if (!RegularUtil.getInstance().isMobileNO(et_phone.getText().toString())) {
            PicToastUtil.getInstance().showToast(RegisterActivity.this, "请输入正确的手机号码!");
            et_phone.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(RegisterActivity.this, et_phone, false);
            return false;
        } else if (TextUtils.isEmpty(et_captcha.getText())) {
            PicToastUtil.getInstance().showToast(RegisterActivity.this, "请输入验证码!");
            et_captcha.requestFocus();
            KeyBoardUtil.getInstance().isCloseSoftInputMethod(RegisterActivity.this, et_phone, false);
            return false;
        }
        return true;
    }

    private class CaptchaCountDownTimer extends CountDownTimer {
        private CaptchaCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            tvCaptcha.setText("重新获取");
            tvCaptcha.setTextColor(getResources().getColor(R.color._blue));
            tvCaptcha.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            try {
                tvCaptcha.setClickable(false);
                tvCaptcha.setTextColor(getResources().getColor(
                        R.color.trans));
                tvCaptcha.setText(String.valueOf(millisUntilFinished / 1000 + "秒"));
            } catch (Resources.NotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (captchaCountDownTimer != null) {
            captchaCountDownTimer.cancel();
            captchaCountDownTimer = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
